// 全局变量
let currentOrder = JSON.parse(localStorage.getItem('currentOrder'));
let cart = JSON.parse(localStorage.getItem('cart')) || [];
let currentUser = JSON.parse(localStorage.getItem('currentUser'));

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    // 更新购物车数量
    updateCartCount();

    // 设置登录状态
    updateLoginStatus();

    // 订单确认页逻辑
    if (window.location.pathname.includes('order.html')) {
        // 检查是否有购物车商品
        if (cart.length === 0) {
            window.location.href = 'cart.html';
            return;
        }

        // 检查是否已登录
        if (!currentUser) {
            localStorage.setItem('redirectAfterLogin', 'order.html');
            window.location.href = 'login.html';
            return;
        }

        // 加载收货信息
        loadShippingInfo();

        // 加载订单商品
        loadOrderItems();

        // 更新订单摘要
        updateOrderSummary();

        // 应用优惠券按钮事件
        document.getElementById('apply-coupon').addEventListener('click', applyCoupon);

        // 提交订单按钮事件
        document.getElementById('place-order').addEventListener('click', placeOrder);

        // 修改收货信息按钮事件
        document.getElementById('edit-shipping').addEventListener('click', function () {
            // 在实际应用中，这里可以跳转到地址编辑页面或显示编辑表单
            alert('在实际应用中，这里会跳转到地址编辑页面');
        });
    }

    // 订单完成页逻辑
    if (window.location.pathname.includes('order-complete.html')) {
        if (!currentOrder) {
            window.location.href = 'index.html';
            return;
        }

        displayOrderComplete();
    }
});

// 加载收货信息
function loadShippingInfo() {
    const shippingInfo = document.getElementById('shipping-info');

    if (currentUser && currentUser.address) {
        shippingInfo.innerHTML = `
            <p><strong>${currentUser.name}</strong></p>
            <p>${currentUser.phone || '电话未填写'}</p>
            <p>${currentUser.address}</p>
        `;
    } else {
        shippingInfo.innerHTML = '<p>请先设置收货地址</p>';
    }
}

// 加载订单商品
function loadOrderItems() {
    const orderItems = document.getElementById('order-items');
    orderItems.innerHTML = '';

    cart.forEach(item => {
        const orderItem = document.createElement('div');
        orderItem.className = 'order-item';
        orderItem.innerHTML = `
            <div class="item-image">
                <img src="${item.image}" alt="${item.name}">
            </div>
            <div class="item-details">
                <h3>${item.name}</h3>
                <div class="item-price">$${item.price.toFixed(2)}</div>
            </div>
            <div class="item-quantity">×${item.quantity}</div>
            <div class="item-total">$${(item.price * item.quantity).toFixed(2)}</div>
        `;
        orderItems.appendChild(orderItem);
    });
}

// 更新订单摘要
function updateOrderSummary() {
    const subtotal = cart.reduce((total, item) => total + (item.price * item.quantity), 0);
    const shipping = subtotal > 50 ? 0 : 5.99;
    const discount = currentOrder && currentOrder.discount ? currentOrder.discount : 0;
    const total = subtotal + shipping - discount;

    document.getElementById('order-subtotal').textContent = `$${subtotal.toFixed(2)}`;
    document.getElementById('order-shipping').textContent = `$${shipping.toFixed(2)}`;
    document.getElementById('order-discount').textContent = `-$${discount.toFixed(2)}`;
    document.getElementById('order-total').textContent = `$${total.toFixed(2)}`;
}

// 应用优惠券
function applyCoupon() {
    const couponCode = document.getElementById('coupon-code').value.trim();

    if (!couponCode) {
        showAlert('请输入优惠码', 'error');
        return;
    }

    // 模拟优惠券验证
    const validCoupons = {
        'WELCOME10': 10,
        'SAVE20': 20,
        'FREESHIP': 5.99
    };

    if (validCoupons[couponCode]) {
        const discount = validCoupons[couponCode];

        // 创建或更新当前订单
        if (!currentOrder) {
            currentOrder = {
                id: generateOrderId(),
                items: [...cart],
                coupon: couponCode,
                discount: discount,
                appliedCoupons: [couponCode]
            };
        } else {
            currentOrder.coupon = couponCode;
            currentOrder.discount = discount;
            if (!currentOrder.appliedCoupons) {
                currentOrder.appliedCoupons = [];
            }
            currentOrder.appliedCoupons.push(couponCode);
        }

        localStorage.setItem('currentOrder', JSON.stringify(currentOrder));
        updateOrderSummary();
        showAlert(`优惠码已应用，节省了 $${discount.toFixed(2)}`, 'success');
    } else {
        showAlert('无效的优惠码', 'error');
    }
}

// 提交订单
function placeOrder() {
    if (!currentUser) {
        showAlert('请先登录', 'error');
        return;
    }

    // 创建订单
    const order = {
        id: generateOrderId(),
        date: new Date().toISOString(),
        items: [...cart],
        subtotal: cart.reduce((total, item) => total + (item.price * item.quantity), 0),
        shipping: cart.reduce((total, item) => total + (item.price * item.quantity), 0) > 50 ? 0 : 5.99,
        discount: currentOrder && currentOrder.discount ? currentOrder.discount : 0,
        paymentMethod: document.querySelector('input[name="payment"]:checked').value,
        status: 'paid',
        shippingInfo: {
            name: currentUser.name,
            phone: currentUser.phone,
            address: currentUser.address
        }
    };

    order.total = order.subtotal + order.shipping - order.discount;

    // 保存订单
    const orders = JSON.parse(localStorage.getItem('orders')) || [];
    orders.push(order);
    localStorage.setItem('orders', JSON.stringify(orders));

    // 添加到用户订单历史
    if (!currentUser.orders) {
        currentUser.orders = [];
    }
    currentUser.orders.push(order.id);
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // 清空购物车
    cart = [];
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCartCount();

    // 保存当前订单用于完成页显示
    localStorage.setItem('currentOrder', JSON.stringify(order));

    // 跳转到订单完成页
    window.location.href = 'order-complete.html';
}

// 显示订单完成信息
function displayOrderComplete() {
    document.getElementById('order-id').textContent = currentOrder.id;
    document.getElementById('complete-total').textContent = `$${currentOrder.total.toFixed(2)}`;

    // 格式化支付方式显示
    const paymentMethods = {
        'alipay': '支付宝',
        'wechat': '微信支付',
        'card': '信用卡/借记卡'
    };
    document.getElementById('complete-payment').textContent = paymentMethods[currentOrder.paymentMethod] || currentOrder.paymentMethod;

    // 显示收货信息
    if (currentOrder.shippingInfo) {
        const shippingInfo = `${currentOrder.shippingInfo.name} | ${currentOrder.shippingInfo.phone} | ${currentOrder.shippingInfo.address}`;
        document.getElementById('complete-shipping').textContent = shippingInfo;
    }

    // 清除当前订单
    localStorage.removeItem('currentOrder');
}

// 生成订单ID
function generateOrderId() {
    return 'ORD_' + Date.now().toString(36).toUpperCase();
}

// 显示提示信息
function showAlert(message, type) {
    // 移除现有的提示
    const existingAlert = document.querySelector('.alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type}`;
    alertDiv.textContent = message;

    const container = document.querySelector('.order-container') || document.querySelector('.order-complete-container');
    if (container) {
        container.insertBefore(alertDiv, container.firstChild);
    } else {
        document.body.insertBefore(alertDiv, document.body.firstChild);
    }

    // 5秒后自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 更新购物车数量显示
function updateCartCount() {
    const count = cart.reduce((total, item) => total + item.quantity, 0);
    const cartCountElement = document.getElementById('cart-count');
    if (cartCountElement) {
        cartCountElement.textContent = count;
    }
}

// 更新登录状态
function updateLoginStatus() {
    const loginLink = document.getElementById('login-link');
    const profileLink = document.querySelector('nav ul li a[href="profile.html"]');

    if (!loginLink) return;

    if (localStorage.getItem('authToken')) {
        loginLink.textContent = '登出';
        loginLink.href = '#';
        loginLink.addEventListener('click', logout);
        if (profileLink) profileLink.style.display = 'block';
    } else {
        loginLink.textContent = '登录';
        loginLink.href = '#';
        loginLink.addEventListener('click', function (e) {
            e.preventDefault();
            localStorage.setItem('redirectAfterLogin', window.location.pathname);
            window.location.href = 'login.html';
        });
        if (profileLink) profileLink.style.display = 'none';
    }
}

// 登出功能
function logout() {
    // 移除认证令牌
    localStorage.removeItem('authToken');
    localStorage.removeItem('userInfo');

    // 更新登录链接文本
    updateLoginStatus();

    // 显示登出提示
    showToast('已成功登出');

    // 刷新页面或执行其他操作
    setTimeout(() => {
        window.location.reload();
    }, 1500);
}

// 显示提示消息
function showToast(message) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;

    // 添加到页面
    document.body.appendChild(toast);

    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    // 3秒后隐藏
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}